package com.lagou.edu.controller;

import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.rpc.EmailFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Optional;
import java.util.Random;


@RestController
@RequestMapping("/code")
public class CodeController {


    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;
    @Autowired
    private EmailFeignClient emailFeignClient;

    /**
     * ⽣成验证码并发送到对应邮箱
     * @return
     */
    @GetMapping("/create/{email}")
    public Boolean create(@PathVariable(value = "email") String email){

        // 删除之前的
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        Example<LagouAuthCode> of = Example.of(lagouAuthCode);
        Optional<LagouAuthCode> one = lagouAuthCodeDao.findOne(of);
        if (one.isPresent()){
            lagouAuthCodeDao.deleteById(one.get().getId());
        }

        // 保存新的
        Random random = new Random();
        Integer code = random.nextInt(999999);
        lagouAuthCode.setCode(code.toString());
        lagouAuthCode.setCreatetime(new Date());
        lagouAuthCode.setExpiretime(new Date(System.currentTimeMillis() + 600000));
        lagouAuthCodeDao.save(lagouAuthCode);

        // 发送邮件
        emailFeignClient.sendEmail(email,code.toString());

        return true;
    }

    /**
     * 校验验证码是否正确，0正确1错误2超时
     * @return 0正确1错误2超时
     */
    @GetMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable(value = "email") String email,
                            @PathVariable(value = "code") String code){
        // 校验验证码
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setCode(code);
        lagouAuthCode.setEmail(email);
        Example<LagouAuthCode> of = Example.of(lagouAuthCode);
        Optional<LagouAuthCode> one = lagouAuthCodeDao.findOne(of);
        if (!one.isPresent() ) {
            return 1;
        }
        if (one.get().getExpiretime().getTime() < new Date().getTime()){
            return 2;
        }
        return 0;
    }


}
